package etcd

import (
	"fmt"
	"gitee.com/zaper/service-config/constant"
	clientv3 "go.etcd.io/etcd/client/v3"
	"sync"
	"time"
)

var (
	etcdClient  *clientv3.Client
	swEtcdMutex sync.Mutex
	err         error
)

func GetEtcdClient() (*clientv3.Client, error) {
	swEtcdMutex.Lock()
	defer swEtcdMutex.Unlock()
	if etcdClient != nil {
		return etcdClient, nil
	}
	etcdClient, err = clientv3.New(clientv3.Config{
		Endpoints: []string{
			fmt.Sprintf("http://%s:2379", constant.LocalHost),
			fmt.Sprintf("http://%s:2381", constant.LocalHost),
			fmt.Sprintf("http://%s:2383", constant.LocalHost),
		},
		DialTimeout:          5 * time.Second,
		DialKeepAliveTimeout: 10 * time.Second,
	})
	if err != nil {
		return nil, err
	}
	return etcdClient, nil
}
